<template>
  <BackgroundImage>
    <!-- 顶部导航 -->
    <TopNavigation :title="isEditMode ? '编辑赛事' : '创建赛事'" backText="赛事业务" :titleSub="isEditMode ? '修改赛事基本信息' : '填写赛事基本信息'" />

    <view class="match-create-container">
      <BoxView :titBoxObj="{
        title: isEditMode ? '编辑赛事' : '创建赛事',
        titleCount: isEditMode ? '修改赛事基本信息' : '填写赛事基本信息'
      }" style="width: 70%;background-color: #FFFFF4;">
        <view class="match-create-form">
          <view class="form-item">
            <text class="form-label">赛事名称 <text class="form-label-required">*</text></text>
            <input class="form-input" v-model="formData.name" placeholder="请输入赛事名称" maxlength="100" />
          </view>
          <view class="form-item">
            <text class="form-label">开始时间 <text class="form-label-required">*</text></text>
            <view class="form-input">
              <picker mode="date" :value="startDate" @change="onStartDateChange">
                <text v-if="startDate">{{ startDate }}</text>
                <text v-else style="color: #969696;">请选择开始日期</text>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">结束时间 <text class="form-label-required">*</text></text>
            <view class="form-input">
              <picker mode="date" :value="endDate" @change="onEndDateChange">
                <text v-if="endDate">{{ endDate }}</text>
                <text v-else style="color: #969696;">请选择结束日期</text>
              </picker>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">赛事状态</text>
            <view class="form-input">

              <picker class="form-picker" :value="statusIndex" :range="statusOptions" @change="onStatusChange">
                <text class="picker-text">{{ statusOptions[statusIndex] }}</text>
              </picker>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">比赛模式</text>
            <view class="form-input">
              <picker class="form-picker" :value="matchModelIndex" :range="matchModelOptions"
                @change="onMatchModelChange">
                <text class="picker-text">{{ matchModelOptions[matchModelIndex] }}</text>
              </picker>

            </view>
          </view>



          <view class="form-item">
            <text class="form-label">赞助商</text>
            <input class="form-input" v-model="formData.sponsor" placeholder="请输入赞助商信息" />
          </view>
          <view class="form-item">
            <text class="form-label">描述</text>
            <view class="form-input" style="height: 100rpx;padding: 4rpx;">
              <textarea v-model="formData.desc" placeholder="请输入赛事描述" maxlength="300"
                style="font-size: 13rpx;height: 100%;" />
            </view>
          </view>
        </view>
        <view class="match-create-button">
          <view class="submit-btn" @click="createMatch" :disabled="loading">
            {{ loading ? (isEditMode ? '编辑中...' : '创建中...') : (isEditMode ? '保存修改' : '创建赛事') }}
          </view>
          <view class="cancel-btn" @click="goBack">取消</view>
        </view>
      </BoxView>
    </view>
  </BackgroundImage>

</template>

<script setup>
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import BackgroundImage from "@/components/BackgroundImage.vue";
import BoxView from "@/components/UiView/BoxView.vue";
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { MatchAPI } from '@/api/battle.js'

// 响应式数据
const loading = ref(false)
const startDate = ref('')
const endDate = ref('')
const statusIndex = ref(0)
const matchModelIndex = ref(0)
const isEditMode = ref(false) // 是否为编辑模式
const editMatchId = ref('') // 编辑的赛事ID

// 表单数据
const formData = ref({
  name: '',
  startTime: 0,
  endTime: 0,
  desc: '',
  sponsor: '',
  status: 0,
  matchModel: 0,
  matchModelId: ''
})

// 状态选项
const statusOptions = ['草稿', '已发布', '进行中', '已结束']
const statusMap = {
  0: 0, // 草稿
  1: 1, // 已发布
  2: 1, // 进行中 (使用已发布状态)
  3: 2  // 已结束
}

// 比赛模式选项 - 固定两个选项
const matchModelOptions = ['普通赛事', '周期赛事']

// 开始日期变化
const onStartDateChange = (e) => {
  startDate.value = e.detail.value
  formData.value.startTime = new Date(e.detail.value).getTime()
}

// 结束日期变化
const onEndDateChange = (e) => {
  endDate.value = e.detail.value
  formData.value.endTime = new Date(e.detail.value + ' 23:59:59').getTime()
}

// 状态选择变化
const onStatusChange = (e) => {
  const index = e.detail.value
  statusIndex.value = index
  formData.value.status = statusMap[index]
}

// 比赛模式选择变化
const onMatchModelChange = (e) => {
  const index = e.detail.value
  matchModelIndex.value = index
  formData.value.matchModel = index // 直接使用索引作为matchModel值
  formData.value.matchModelId = `model_${index}` // 生成对应的matchModelId
}

// 加载比赛模式列表 - 不再需要从API获取
const loadMatchModels = () => {
  // 设置默认选择第一个（普通赛事）
  formData.value.matchModel = 0
  formData.value.matchModelId = 'model_0'
}

// 创建或编辑赛事
const createMatch = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入赛事名称',
      icon: 'none'
    })
    return
  }

  if (!formData.value.startTime) {
    uni.showToast({
      title: '请选择开始时间',
      icon: 'none'
    })
    return
  }

  if (!formData.value.endTime) {
    uni.showToast({
      title: '请选择结束时间',
      icon: 'none'
    })
    return
  }

  if (formData.value.endTime <= formData.value.startTime) {
    uni.showToast({
      title: '结束时间必须大于开始时间',
      icon: 'none'
    })
    return
  }

  loading.value = true
  try {
    let result
    if (isEditMode.value) {
      // 编辑模式：调用编辑接口
      result = await MatchAPI.edit({
        matchId: editMatchId.value,
        name: formData.value.name,
        startTime: formData.value.startTime,
        endTime: formData.value.endTime,
        desc: formData.value.desc,
        sponsor: formData.value.sponsor,
        status: formData.value.status,
        matchModel: formData.value.matchModel,
        matchModelId: formData.value.matchModelId,
        createUserID: formData.value.createUserID || 'current_user'
      })
      console.log('编辑赛事API返回结果:', result)
    } else {
      // 创建模式：调用创建接口
      result = await MatchAPI.create({
        matchId: `match_${Date.now()}`,
        name: formData.value.name,
        startTime: formData.value.startTime,
        endTime: formData.value.endTime,
        desc: formData.value.desc,
        sponsor: formData.value.sponsor,
        status: formData.value.status,
        matchModel: formData.value.matchModel,
        matchModelId: formData.value.matchModelId,
        createUserID: 'current_user' // 这里应该从用户状态获取
      })
      console.log('创建赛事API返回结果:', result)
    }

    if (result.code === 0) {
      uni.showToast({
        title: isEditMode.value ? '赛事编辑成功' : '赛事创建成功',
        icon: 'success'
      })

      // 设置刷新标记，通知列表页面刷新数据
      uni.setStorageSync('matchListNeedRefresh', true)
      console.log('已设置刷新标记，返回后将刷新列表')

      // 延迟返回上一页
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      throw new Error(result.msg || (isEditMode.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    console.error(isEditMode.value ? '编辑赛事失败:' : '创建赛事失败:', error)
    uni.showToast({
      title: error.message || (isEditMode.value ? '编辑失败' : '创建失败'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  // 清除编辑数据
  uni.removeStorageSync('editMatchData')
  uni.navigateBack()
}

// 加载编辑数据
const loadEditData = () => {
  try {
    console.log('开始加载编辑数据...')
    const editData = uni.getStorageSync('editMatchData')
    console.log('读取到的编辑数据:', editData)
    if (editData) {
      // 如果是字符串，需要解析
      const data = typeof editData === 'string' ? JSON.parse(editData) : editData
      console.log('解析后的编辑数据:', data)
      isEditMode.value = true
      editMatchId.value = data.id || data.matchId
      
      // 填充表单数据
      formData.value = {
        name: data.name || '',
        startTime: data.startTime || 0,
        endTime: data.endTime || 0,
        desc: data.desc || '',
        sponsor: data.sponsor || '',
        status: data.status !== undefined ? data.status : 0,
        matchModel: data.matchModel !== undefined ? data.matchModel : 0,
        matchModelId: data.matchModelId || '',
        createUserID: data.createUserID || ''
      }
      console.log('表单数据已填充:', formData.value)
      
      // 设置日期显示
      if (data.startTime) {
        const startDateObj = new Date(data.startTime)
        startDate.value = `${startDateObj.getFullYear()}-${String(startDateObj.getMonth() + 1).padStart(2, '0')}-${String(startDateObj.getDate()).padStart(2, '0')}`
        console.log('开始日期已设置:', startDate.value)
      }
      
      if (data.endTime) {
        const endDateObj = new Date(data.endTime)
        endDate.value = `${endDateObj.getFullYear()}-${String(endDateObj.getMonth() + 1).padStart(2, '0')}-${String(endDateObj.getDate()).padStart(2, '0')}`
        console.log('结束日期已设置:', endDate.value)
      }
      
      // 设置状态索引
      // 根据状态值找到对应的索引
      // match-query 中的状态: 0=待开始, 1=进行中, 2=已结束
      // match-create 中的状态选项: 0=草稿, 1=已发布, 2=进行中, 3=已结束
      const statusValue = data.status
      if (statusValue === 0) {
        statusIndex.value = 0 // 待开始 -> 草稿
      } else if (statusValue === 1) {
        statusIndex.value = 2 // 进行中 -> 进行中
      } else if (statusValue === 2) {
        statusIndex.value = 3 // 已结束 -> 已结束
      }
      console.log('状态索引已设置:', statusIndex.value)
      
      // 设置比赛模式索引
      if (data.matchModel !== undefined) {
        matchModelIndex.value = data.matchModel
        console.log('比赛模式索引已设置:', matchModelIndex.value)
      }
      
      console.log('编辑数据加载完成，编辑模式已启用')
    } else {
      console.log('未找到编辑数据，使用创建模式')
    }
  } catch (error) {
    console.error('加载编辑数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  }
}

// 页面卸载时清除编辑数据
onBeforeUnmount(() => {
  uni.removeStorageSync('editMatchData')
})

// 页面加载时获取比赛模式列表和编辑数据
onMounted(() => {
  loadMatchModels()
  loadEditData()
})
</script>

<style lang="scss" scoped>
.match-create-button {
  display: flex;
  justify-content: center;
  align-items: center;
  // margin-top: 5rpx;

  view {
    height: 30rpx;
    width: 118rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14rpx;
  }

  .submit-btn {
    color: #FFFFFF;
    background: url('/static/buttons/button6.png') no-repeat center center;
    background-size: 100% 100%;
  }

  .cancel-btn {
    background: url('/static/buttons/button7.png') no-repeat center center;
    background-size: 100% 100%;
    color: #FFFFFF;
  }
}


.match-create-form {
  background-color: #F0F0E4;
  overflow: auto;
  border-radius: 10rpx;
  margin: 10rpx;
  margin-bottom: 5rpx;
  padding: 10rpx;
  height: calc(100% - 100rpx);

  .form-item {
    display: flex;
    align-items: start;
    margin-bottom: 10rpx;

    .form-label {
      font-size: 14rpx;
      width: 80rpx;
      text-align: right;
      color: #333;

      .form-label-required {
        color: orangered;
      }
    }

    .form-input {
      margin-left: 10rpx;
      height: 26rpx;
      line-height: 26rpx;
      padding: 0 10rpx;
      font-size: 13rpx;
      color: #000000;
      background-color: #DADADA;
      border-radius: 4rpx;
      width: 60%;
    }
  }
}

.match-create-container {
  height: calc(100vh - 55rpx);
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 20rpx;
}
</style>